//
//  WYBusinessDetailController.m
//  Boss
//
//  Created by admin on 2018/7/6.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "WYBusinessDetailController.h"
#import "WYBusinessDetailBottomView.h"
#import "WYCommentView.h"
#import "WYProgrammeController.h"
#import "NSString+Extension.h"
#import "WYShareBottomView.h"
#import <JavaScriptCore/JSContext.h>
#import <JavaScriptCore/JavaScriptCore.h>
#import "UIWebView+TS_JavaScriptContext.h"
@protocol JSObjcDelegate <JSExport>
// AndroidWebView对象调用的JavaScript方法，必须声明！！！
-(NSString *)waitJS;
-(NSString *)getMessage;
@end


@interface WYBusinessDetailController ()<WYBusinessDetailBottomViewDelegate,WYCommentViewDelegate,UIWebViewDelegate,JSObjcDelegate,TSWebViewDelegate>
@property (nonatomic,strong)UIWebView *webView;
@property (nonatomic,strong)WYCommentView *commentView;
@property (nonatomic,strong)WYProgrammeController *pvc;
@property (nonatomic,strong)UIButton *buton;

@property (nonatomic,strong)WYBusinessDetailBottomView *bottomView;
@property (nonatomic,assign)NSUInteger collectinType;
@property (nonatomic,strong)NSString *opportunityId;
@property (nonatomic,strong)WYShareBottomView *shareBottomView;

@property (nonatomic,strong)UIImageView *imageView;
@property (nonatomic,assign)NSUInteger type;

@property (nonatomic,strong)MBProgressHUD *hud;

@property (nonatomic,strong)JSContext *context;

@end

@implementation WYBusinessDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.imageView = [[UIImageView alloc]init];
    [self.view addSubview:self.imageView];
    self.imageView.frame = CGRectMake(0, 0, 5, 5);
    self.imageView.hidden = YES;
    
    [self setupUI];
    [self loadData];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"通用_返回白"] style:(UIBarButtonItemStyleDone) target:self action:@selector(returnToTop)];
//    NSString *str = @"http://192.168.1.158:8091/view/ftl/opportunity_3.html?businessName=1&userId=82";
//   NSString *test = [str getNavTitle];
    
    // 1.创建正则表达式
//    NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil];
//    // 2.测试字符串
//    NSArray *results = [regex matchesInString:self options:0 range:NSMakeRange(0, self.length)];
//    
//    return results.count > 0;
}
-(void)returnToTop
{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    
    
    
}



-(void)loadData
{
    WEAKSELF
    [WYHttpServer gettoBusinessTemplateWithOpportunityId:self.urlString WithBussinessCode:self.bussinessCode SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            [weakSelf.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:response[@"result"]]]];
        }
    }];
    
    
    [WYHttpServer getIsCollectWithOpportunityId:self.urlString SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            weakSelf.shareBottomView.kLinkTitle = response[@"name"];
        }
    }];
    
}

- (void)webView:(UIWebView *)webView didCreateJavaScriptContext:(JSContext *)ctx
{
    ctx[@"ios"] = self;
}



-(void)webViewDidStartLoad:(UIWebView *)webView
{
    self.context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    self.context [@"ios"] = self;
    self.context.exceptionHandler = ^(JSContext *context, JSValue *exception) {
        context.exception = exception;
        NSLog(@"----------------------------------------------------------------------------------------------------------------------------------------------------%@",exception);
    };
    
    
    
    
    
    
    
//     NSString *jsStr =  @"var downloadWrap = document.getElementById('downloadWrap');downloadWrap.parentNode.removeChild(downloadWrap)";
//     [webView stringByEvaluatingJavaScriptFromString:jsStr];
//    self.context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    // context = self;、
//    WYBusinessDetailController *bvc = [[WYBusinessDetailController alloc]init];
//    WEAKSELF
////    self.context [@"ios"] = bvc;
////    self.context [@"Android"] = bvc;
//    self.context.exceptionHandler = ^(JSContext *context, JSValue *exception) {
//        context.exception = exception;
//
//
//
//        NSLog(@"--------------------\n%@--------------------\n",exception);
//       // NSLog(@"%@",context);
//
//
////        weakSelf.context[@"getMessage"]=  ^(NSString *name) {
////            return [weakSelf getMessage];
////        };
////       weakSelf.context[@"waitJS"]=  ^(NSString *name) {
////            return [weakSelf waitJS];
////        };
//    };


//    weakSelf.context[@"getMessage"]=  ^(NSString *name) {
//        return [weakSelf getMessage];
//    };
//    weakSelf.context[@"waitJS"]=  ^(NSString *name) {
//        return [weakSelf waitJS];
//    };
}
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    
    self.context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    self.context [@"ios"] = self;
    
//    self.context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//
//    // context = self;
//    WEAKSELF
//    self.context [@"ios"] = self;
//    self.context.exceptionHandler = ^(JSContext *context, JSValue *exception) {
//        context.exception = exception;
//        NSLog(@"----------------------------------------------------------------------------------------------------------------------------------------------------%@",exception);
//    };
    
    
//    context.exceptionHandler = ^(JSContext *context, JSValue *exception) {
//        context[@"waitJS"]=  ^(NSString *name) {
//            return [weakSelf waitJS];
//        };
//        weakSelf.context[@"getMessage"]=  ^(NSString *name) {
//            return [weakSelf getMessage];
//        };
//    };

//    weakSelf.context[@"getMessage"]=  ^(NSString *name) {
//        return [weakSelf getMessage];
//    };
//    weakSelf.context[@"waitJS"]=  ^(NSString *name) {
//        return [weakSelf waitJS];
//    };
//
//    NSString *jsStr =  @"var downloadWrap = document.getElementById('downloadWrap');downloadWrap.parentNode.removeChild(downloadWrap)";
//    [webView stringByEvaluatingJavaScriptFromString:jsStr];
    
    
    
//    self.webView
    [self loadCollectionStatusType];
    NSString *opportunityId = [self.webView stringByEvaluatingJavaScriptFromString:@"getOpportunityId();"];
    self.opportunityId = opportunityId;
    NSString *urlString = webView.request.URL.absoluteString;
    if ([urlString rangeOfString:@"/view/ftl/opportunity"].location != NSNotFound) {
        if ([urlString rangeOfString:@"businessName="].location!=NSNotFound) {
            
            NSRange range = [urlString rangeOfString:@"businessName="];
            NSRange range2 = [urlString rangeOfString:@"&"];
            
            NSString *str = [urlString substringWithRange:NSMakeRange(range.location+range.length, range2.location-range.location-range.length)];
            NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)str, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));

            self.navTitle = str;
            self.navigationItem.title = decodedString;
            
            
            
            
        }

    }
  
}

-(NSString *)waitJS
{
    return @"iOS";
}
-(NSString *)getMessage
{
    return @"iOS";
}
-(void)loadBussiness
{
    if (self.opportunityId.length) {
        
    }else{
        NSString *opportunityId = [self.webView stringByEvaluatingJavaScriptFromString:@"getOpportunityId();"];
        if (opportunityId.length) {
            self.opportunityId = opportunityId;
        }
    }
    
    
    WEAKSELF
    [WYHttpServer shareToOpportunityId:self.opportunityId SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        
        dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.hud hideAnimated:YES];
            });
        });
        
        if (success) {
            [self.imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@!default",response[@"result"][@"pic"]]] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                [weakSelf.shareBottomView setShareImage:image];
                NSString *title = response[@"result"][@"name"];
                title = [NSString stringWithFormat:@"【巨牛BOSS】分享-%@",title];
                [weakSelf.shareBottomView setKLinkTitle:title];
                [weakSelf.shareBottomView setKLinkURL:response[@"result"][@"url"]];
                [weakSelf.shareBottomView setKLinkDescription:response[@"result"][@"message"]];
//                [weakSelf.shareBottomView setKLinkDescription:@"123\\\\n456"];
                weakSelf.shareBottomView.wait = NO;
                
                switch (weakSelf.type) {
                    case 0:{
                        [weakSelf.shareBottomView weChatShare:nil];
                    }
                        break;
                    case 1:{
                        [weakSelf.shareBottomView friendShatre:nil];
                    }
                        break;
                    case 2:{
                        [weakSelf.shareBottomView qqShare:nil];
                    }
                        break;
                    case 3:{
                        [weakSelf.shareBottomView QQZoneShare:nil];
                    }
                        break;
                    case 4:{
                        [weakSelf.shareBottomView weiBoShare:nil];
                    }
                        break;
                    default:
                        break;
                }
                
                
                
                
                
                
            }];
            
            
            
            
        }
        
        
    }];
}

-(void)loadCollectionStatusType
{
    WEAKSELF
    NSString *opportunityId = [self.webView stringByEvaluatingJavaScriptFromString:@"getOpportunityId();"];
    self.opportunityId = opportunityId;
    NSLog(@"%@",opportunityId);
    [WYHttpServer getIsCollectWithOpportunityId:opportunityId SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            weakSelf.collectinType = [response[@"result"] integerValue];
            if (weakSelf.collectinType==1) {
                weakSelf.bottomView.collectionImageView.image = [UIImage imageNamed:@"collection_selected"];
                
            }else{
                weakSelf.bottomView.collectionImageView.image = [UIImage imageNamed:@"collection_normal"];
            }
        }
    }];
}

-(void)setupUI
{
    self.navigationItem.title = self.navTitle;
    self.webView = [[UIWebView alloc]init];
    self.webView.frame = CGRectMake(0, self.navHeight, kScreenWidth, kScreenHeight-self.navHeight-self.tabHeight-10);
    self.webView.delegate = self;
    [self.view addSubview:self.webView];
   
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlString]]];
    self.webView.scrollView.bounces = NO;
    UIView *backBottomView = [[UIView alloc]init];
    [self.view addSubview:backBottomView];
    [backBottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(self.tabHeight+5);
    }];
    backBottomView.backgroundColor = [UIColor whiteColor];
    
    WYBusinessDetailBottomView *bottomView = [WYBusinessDetailBottomView initWithDetailBottomView];
    [bottomView.getBtn setBackgroundColor:[UIColor hexStringToColor:@"#d8593f" alpha:1.0]];
    self.bottomView = bottomView;
    [backBottomView addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        make.height.mas_equalTo(50);
    }];
    bottomView.delegate = self;
    
    self.commentView= [[WYCommentView alloc]init];
    self.commentView.delegate = self;
//    [self.view addSubview:self.maskView];
//    self.maskView.hidden = YES;
   [self.view addSubview:self.commentView];
    
    [self.commentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(164);
        make.bottom.mas_equalTo(164);
    }];
    self.commentView.comment.text = @"项目问答";
    self.commentView.textView.placeholder = @"请输入您想咨询的问题";
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)name:UIKeyboardWillHideNotification
                                               object:nil];
    
   

     [self.view addSubview:self.shareBottomView];
    WEAKSELF
    self.shareBottomView.complete = ^(NSUInteger type) {
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    // Change the background view style and color.
    self.hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
    self.hud.backgroundView.color = [UIColor colorWithWhite:0.f alpha:0.4f];
    self.hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    self.hud.bezelView.backgroundColor = [UIColor colorWithWhite:0.f alpha:0.4];
        
        
      weakSelf.type = type;
      [weakSelf loadBussiness];
      
    };
}
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    if (self.commentView.textView.isFirstResponder) {
        NSDictionary *userInfo = [aNotification userInfo];
        NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
        CGRect keyboardRect = [aValue CGRectValue];
        CGFloat height = keyboardRect.size.height;
        //self.comment

            [self.commentView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.bottom.mas_equalTo(-height);
            }];
//            self.commentView.frame = CGRectMake(0, kScreenHeight-height, kScreenWidth, 164);
//
            

        
        
       
//        [self.view addSubview:self.maskView];
//
         self.maskView.hidden = NO;
    }
    
    
    
    
}
- (void)keyboardWillHide:(NSNotification *)aNotification{
    [self.commentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(164);
    }];
//     self.maskView.hidden = YES;
//    [self.maskView removeFromSuperview];
//    [self.commentView removeFromSuperview];
}
- (void)didCollectionView:(UIImageView *)imageView
{
    WEAKSELF
    [WYHttpServer getCollectionWithOpportunityId:self.urlString WithType:self.collectinType==1?@"2":@"1" SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
       
        if (success) {
            weakSelf.collectinType = [response[@"result"] integerValue];
            if (weakSelf.collectinType==1) {
                [weakSelf toast:@"收藏成功"];
                weakSelf.bottomView.collectionImageView.image = [UIImage imageNamed:@"collection_selected"];
            }else{
                [weakSelf toast:@"取消收藏"];
                weakSelf.bottomView.collectionImageView.image = [UIImage imageNamed:@"collection_normal"];
            }
        }
        
        
    }];
}
-(void)clickQuestionAction
{
     [self.commentView.textView becomeFirstResponder];
}
-(void)clickShareAction
{
    self.shareBottomView.wait = YES;
    self.shareBottomView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
}
-(void)clickContantAction
{
    
    NSString *str1 = [self.webView stringByEvaluatingJavaScriptFromString:@"getPhoneNumber();"];
    
    
    
    NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", str1];
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone] options:@{} completionHandler:nil];
    } else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
    }
}
-(void)getProgrammeAction
{
    WEAKSELF

    UIButton *button = [[UIButton alloc]initWithFrame:SCREEN_BOUNDS];
    button.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    self.buton = button;
    [button addTarget:self action:@selector(clickmaskView) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    
//    [[UIApplication sharedApplication].keyWindow addSubview:self.buton];
    [self.view addSubview:self.buton];
    if (!self.pvc) {
         self.pvc = [[WYProgrammeController alloc]init];
    }
    
    [[UIApplication sharedApplication].keyWindow addSubview:self.pvc.view];
     self.pvc.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    
    self.pvc.backComplete = ^{
        [weakSelf.pvc.view removeFromSuperview];
        [weakSelf.buton removeFromSuperview];
    };
    
    self.pvc.Complete = ^(NSString *name, NSString *moble, NSString *code, NSString *address, NSString *message, NSUInteger type) {
        NSString *sex =@"";
        if (type==1) {
            sex = @"男";
        }else{
            sex = @"女";
        }
        if (!name.length) {
            [weakSelf toast:@"请输入您的姓名"];return ;
        }
        if (!moble.length) {
            [weakSelf toast:@"请输入手机号"];return;
        }
        if (!code.length) {
            [weakSelf toast:@"请输入验证码"]; return;
        }
        if (!address.length) {
            [weakSelf toast:@"请选择您的开店地址"];return;
        }
        
        
        
        [WYHttpServer getApplySchemeWithBusinessCode:weakSelf.opportunityId WithName:name WithSex:sex WithPhone:moble WithVerifyCode:code WithAddress:address WithComment:message SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
            
            if (success) {
                
                [weakSelf.pvc.view removeFromSuperview];
                [weakSelf.buton removeFromSuperview];
                [weakSelf setPvc:nil];
                [weakSelf toast:@"提交成功"];
            }else{
                [weakSelf toast:errorMessage];
            }
            
            
            
            
        }];
        
    };
    
    
    
    
    
    
    
    
    
}
-(void)clickmaskView
{
    [self.buton removeFromSuperview];
    [self.pvc.view removeFromSuperview];
}
#pragma mark commentView
- (void)clickSendButton
{
    if (!self.commentView.textView.text.length) {
        [self toast:@"请输入您想咨询的问题"]; return;
    }
    
    
    [WYHttpServer sendAskWithOpportunityId:self.urlString WithComment:self.commentView.textView.text SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            
            
            
        }
    }];
    
    
    
    
    
    
}
- (void)clickCloseButton
{
    
}

-(WYShareBottomView *)shareBottomView
{
    if (!_shareBottomView) {
        _shareBottomView = [WYShareBottomView shareedShareBottomView];
        [_shareBottomView setBottomHeightStr:@""];
        _shareBottomView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, kScreenHeight);
        //_shareBottomView.wait = YES;
    }
    return _shareBottomView;
}



@end
